import React, { useState, useRef, useEffect } from 'react';
import { ChatSession, ChatMessage } from '../../KimiChat';
import { Input, Button, Typography, Space, Card, Avatar, Divider, Empty, Badge } from 'antd';
import { SendOutlined, CheckOutlined, CloseOutlined, RobotOutlined, UserOutlined, MessageOutlined } from '@ant-design/icons';
import './ChatContent.scss';

interface ChatContentProps {
    session: ChatSession | undefined;
    onSendMessage: (content: string) => void;
    isWaitingForResponse: boolean;
    pendingResponses: ChatMessage[];
    streamingMessages: ChatMessage[];
    onAcceptResponse: (messageId: string) => void;
    onRejectResponse: (messageId: string) => void;
    onAcceptAllResponses: () => void;
    onRejectAllResponses: () => void;
}

const ChatContent: React.FC<ChatContentProps> = ({ 
    session, 
    onSendMessage, 
    isWaitingForResponse, 
    pendingResponses, 
    streamingMessages,
    onAcceptResponse, 
    onRejectResponse,
    onAcceptAllResponses,
    onRejectAllResponses
}) => {
    const [inputValue, setInputValue] = useState('');
    const [isComposing, setIsComposing] = useState(false);
    const messagesEndRef = useRef<HTMLDivElement>(null);
    const textareaRef = useRef<HTMLTextAreaElement>(null);

    const scrollToBottom = () => {
        messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
    };

    useEffect(() => {
        scrollToBottom();
    }, [session?.messages, pendingResponses, streamingMessages]);

    const handleSubmit = (e: React.FormEvent) => {
        e.preventDefault();
        if (inputValue.trim() && !isComposing && !isWaitingForResponse) {
            onSendMessage(inputValue.trim());
            setInputValue('');
            // 重置textarea高度
            if (textareaRef.current) {
                textareaRef.current.style.height = 'auto';
            }
        }
    };

    const handleKeyDown = (e: React.KeyboardEvent) => {
        if (e.key === 'Enter' && !e.shiftKey && !isComposing) {
            e.preventDefault();
            handleSubmit(e);
        }
    };

    const handleInputChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
        setInputValue(e.target.value);
        
        // 自动调整textarea高度
        const textarea = e.target;
        textarea.style.height = 'auto';
        textarea.style.height = Math.min(textarea.scrollHeight, 120) + 'px';
    };

    const formatTime = (date: Date) => {
        return date.toLocaleTimeString('zh-CN', {
            hour: '2-digit',
            minute: '2-digit'
        });
    };

    // 文本显示组件（无打字机效果）
    const TypewriterText: React.FC<{ text: string; speed?: number }> = ({ text }) => {
        return (
            <span>
                {text}
            </span>
        );
    };

    const renderMessage = (message: ChatMessage) => {
        return (
            <div
                key={message.id}
                className={`chat-message chat-message--${message.type}`}
            >
                <div className="chat-message__avatar">
                    {message.type === 'user' ? (
                        <Avatar icon={<UserOutlined />} className="chat-message__user-avatar" />
                    ) : (
                        <Avatar icon={<RobotOutlined />} className="chat-message__assistant-avatar" />
                    )}
                </div>
                <div className="chat-message__content">
                    <div className="chat-message__header">
                        <Typography.Text strong className="chat-message__sender">
                            {message.type === 'user' ? '您' : 'Kimi'}
                        </Typography.Text>
                        <Typography.Text type="secondary" className="chat-message__time">
                            {formatTime(message.timestamp)}
                        </Typography.Text>
                    </div>
                    <Typography.Paragraph className="chat-message__text">
                        {message.content}
                    </Typography.Paragraph>
                </div>
            </div>
        );
    };
    
    const renderStreamingMessage = (message: ChatMessage) => {
        return (
            <div
                key={message.id}
                className="chat-message chat-message--streaming"
            >
                <div className="chat-message__avatar">
                    <Avatar icon={<RobotOutlined />} className="chat-message__assistant-avatar" />
                </div>
                <div className="chat-message__content">
                    <div className="chat-message__header">
                        <Space>
                            <Typography.Text strong className="chat-message__sender">
                                Kimi
                            </Typography.Text>
                            <Badge status="processing" text="生成中" />
                        </Space>
                        <Typography.Text type="secondary" className="chat-message__time">
                            {formatTime(message.timestamp)}
                        </Typography.Text>
                    </div>
                    <Typography.Paragraph className="chat-message__text chat-message__text--streaming">
                        <TypewriterText text={message.streamingContent || ''} speed={20} />
                    </Typography.Paragraph>
                </div>
            </div>
        );
    };

    const renderPendingMessage = (message: ChatMessage) => {
        return (
            <div
                key={message.id}
                className="chat-message chat-message--pending"
            >
                <div className="chat-message__avatar">
                    <Avatar icon={<RobotOutlined />} className="chat-message__assistant-avatar" />
                </div>
                <div className="chat-message__content">
                    <div className="chat-message__header">
                        <Space>
                            <Typography.Text strong className="chat-message__sender">
                                Kimi
                            </Typography.Text>
                            <Badge status="warning" text="待确认" />
                        </Space>
                        <Typography.Text type="secondary" className="chat-message__time">
                            {formatTime(message.timestamp)}
                        </Typography.Text>
                    </div>
                    <Typography.Paragraph className="chat-message__text">
                        {message.content}
                    </Typography.Paragraph>
                    <div className="chat-message__actions">
                        <Button 
                            type="primary"
                            size="small"
                            icon={<CheckOutlined />}
                            onClick={() => onAcceptResponse(message.id)}
                        >
                            采用
                        </Button>
                        <Button 
                            danger
                            size="small"
                            icon={<CloseOutlined />}
                            onClick={() => onRejectResponse(message.id)}
                        >
                            放弃
                        </Button>
                    </div>
                </div>
            </div>
        );
    };

    if (!session) {
        return (
            <div className="chat-content">
                <div className="chat-content__empty">
                    <Empty
                        image={Empty.PRESENTED_IMAGE_DEFAULT}
                        description={
                            <Space direction="vertical" align="center">
                                <Typography.Title level={3}>欢迎使用 Kimi Chat</Typography.Title>
                                <Typography.Text>选择一个对话或创建新对话开始聊天</Typography.Text>
                            </Space>
                        }
                    />
                    <Divider>功能特点</Divider>
                    <div className="chat-content__features">
                        <Card className="chat-content__feature">
                            <Card.Meta 
                                avatar={<Avatar icon={<MessageOutlined />} />}
                                title="智能数据分析"
                            />
                        </Card>
                        <Card className="chat-content__feature">
                            <Card.Meta 
                                avatar={<Avatar icon={<MessageOutlined />} />}
                                title="实时图表展示"
                            />
                        </Card>
                        <Card className="chat-content__feature">
                            <Card.Meta 
                                avatar={<Avatar icon={<MessageOutlined />} />}
                                title="数据筛选排序"
                            />
                        </Card>
                    </div>
                </div>
            </div>
        );
    }

    return (
        <div className="chat-content">
            <div className="chat-content__header">
                <Typography.Title level={4} className="chat-content__title">{session.title}</Typography.Title>
                <Badge count={session.messages.length} showZero className="chat-content__meta" />
            </div>
            
            <div className="chat-content__messages">
                {session.messages.length === 0 && pendingResponses.length === 0 && streamingMessages.length === 0 ? (
                    <div className="chat-content__welcome">
                        <Empty
                            image={Empty.PRESENTED_IMAGE_SIMPLE}
                            description={
                                <Space direction="vertical" align="center">
                                    <Typography.Title level={5}>开始新的对话吧！</Typography.Title>
                                    <Typography.Text type="secondary">输入您的问题，我会为您分析并展示相关数据</Typography.Text>
                                </Space>
                            }
                        />
                    </div>
                ) : (
                    <>
                        {session.messages
                            .sort((a, b) => new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime())
                            .map(renderMessage)}
                        {pendingResponses
                            .sort((a, b) => new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime())
                            .map(renderPendingMessage)}
                        {streamingMessages
                            .sort((a, b) => new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime())
                            .map(renderStreamingMessage)}
                    </>
                )}
                <div ref={messagesEndRef} />
            </div>
            
            {pendingResponses.length > 0 && (
                <div className="chat-content__pending-actions">
                    <div className="chat-content__pending-info">
                        <Badge count={pendingResponses.length} color="warning" />
                        <Typography.Text strong style={{ marginLeft: 8 }}>
                            条待确认回复
                        </Typography.Text>
                    </div>
                    <div className="chat-content__pending-buttons">
                        <Button 
                            type="primary"
                            icon={<CheckOutlined />}
                            onClick={onAcceptAllResponses}
                        >
                            全部采用
                        </Button>
                        <Button 
                            danger
                            icon={<CloseOutlined />}
                            onClick={onRejectAllResponses}
                        >
                            全部放弃
                        </Button>
                    </div>
                </div>
            )}
            
            <div className="chat-content__input-area">
                <form onSubmit={handleSubmit} className="chat-content__form">
                    <div className="chat-content__input-wrapper">
                        <Input.TextArea
                            ref={textareaRef}
                            value={inputValue}
                            onChange={handleInputChange}
                            onKeyDown={handleKeyDown}
                            onCompositionStart={() => setIsComposing(true)}
                            onCompositionEnd={() => setIsComposing(false)}
                            placeholder={isWaitingForResponse ? "等待回复中..." : "输入消息... (Shift + Enter 换行)"}
                            className="chat-content__input"
                            rows={1}
                            disabled={isWaitingForResponse}
                            autoSize={{ minRows: 1, maxRows: 4 }}
                        />
                        <Button
                            type="primary"
                            icon={<SendOutlined />}
                            disabled={!inputValue.trim() || isComposing || isWaitingForResponse}
                            loading={isWaitingForResponse}
                            onClick={handleSubmit}
                            shape="circle"
                            className="chat-content__send-button"
                        />
                    </div>
                </form>
            </div>
        </div>
    );
};

export default ChatContent;